<template>
  <div class="register-container">
    <!-- 左侧背景 -->
    <div class="left-section">
      <transition-group name="fade">
        <img v-for="(bg, index) in backgroundImages" :key="index" :src="bg"
          :class="['bg-image', { active: currentBgIndex === index }]" alt="京剧背景">
      </transition-group>
      <div class="content-overlay"></div>
    </div>

    <!-- 右侧注册区域 -->
    <div class="right-section">
      <div class="right-content">
        <!-- 标题部分 -->
        <div class="title-section">
          <h1>京剧苑</h1>
          <p>传承国粹 · 弘扬文化</p>
        </div>

        <!-- 注册表单 -->
        <div class="register-box">
          <h2 class="form-title">用户注册</h2>
          <el-form ref="registerForm" :model="registerForm" :rules="registerRules">
            <!-- 用户名 -->
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"
                show-password></el-input>
            </el-form-item>

            <!-- 确认密码 -->
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码"
                prefix-icon="el-icon-lock" show-password></el-input>
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item prop="phone">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone"></el-input>
            </el-form-item>

            <!-- 手机验证码 -->
            <el-form-item prop="phoneCode">
              <div class="code-input-group">
                <el-input v-model="registerForm.phoneCode" placeholder="请输入手机验证码" prefix-icon="el-icon-key"></el-input>
                <el-button class="code-btn" @click="sendPhoneCode" :disabled="phoneCodeTimer > 0">
                  {{ phoneCodeTimer > 0 ? `${phoneCodeTimer}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <!-- 邮箱 -->
            <el-form-item prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱（选填）" prefix-icon="el-icon-message"></el-input>
            </el-form-item>

            <!-- 注册按钮 -->
            <el-button type="primary" @click="handleRegister" :loading="loading">注册</el-button>
          </el-form>

          <div class="login-link">
            已有账号？<router-link to="/login">立即登录</router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import bg1 from '@/assets/opera_bg1.jpg'
import bg2 from '@/assets/opera_bg2.jpg'
import bg3 from '@/assets/opera_bg3.jpg'
import service from '@/utils/request'
import CryptoJS from 'crypto-js' 

export default {
  data() {
    // 确认密码的验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    // const encryptPassword = (password) => {
    //   return CryptoJS.MD5(password).toString();
    // }

    return {
      loading: false,
      phoneCodeTimer: 0,
      emailCodeTimer: 0,
      backgroundImages: [bg1, bg2, bg3],
      currentBgIndex: 0,
      bgRotationTimer: null,
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        phoneCode: '',
        email: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        phoneCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 设置页面标题
    document.title = '京剧苑 - 用户注册';
    // 启动背景图轮播
    this.startBackgroundRotation();
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.bgRotationTimer) {
      clearInterval(this.bgRotationTimer);
    }
  },
  methods: {
    // 开始背景图轮播
    startBackgroundRotation() {
      this.bgRotationTimer = setInterval(() => {
        this.currentBgIndex = (this.currentBgIndex + 1) % this.backgroundImages.length;
      }, 5000);
    },
    // 发送手机验证码
    sendPhoneCode() {
      this.$refs.registerForm.validateField('phone', valid => {
        if (!valid) {
          service.get('/api/system/verification/send-phone-code', {
            params: {
              phone: this.registerForm.phone
            }
          })
            .then(res => {
              if (res.code === 200) {
                this.$message.success('验证码已发送')
                this.phoneCodeTimer = 60
                const timer = setInterval(() => {
                  this.phoneCodeTimer--
                  if (this.phoneCodeTimer <= 0) {
                    clearInterval(timer)
                  }
                }, 1000)
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.$message.error('发送失败，请稍后重试')
              console.error(err)
            })
        }
      })
    },

    // 处理注册
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true

          const submitData = {
            ...this.registerForm,
            password: CryptoJS.MD5(this.registerForm.password).toString()
          }
          delete submitData.confirmPassword

          service.post('/api/system/user/register', submitData)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('注册成功')
                this.$router.push('/login')
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.$message.error('注册失败，请稍后重试')
              console.error(err)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  min-height: 100vh;
  width: 100vw;
  overflow: hidden;
}

/* 左侧样式 */
.left-section {
  flex: 1.2;
  position: relative;
  overflow: hidden;
}

.bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.bg-image.active {
  opacity: 1;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.content-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(139, 0, 0, 0.6), rgba(0, 0, 0, 0.6));
}

/* 右侧样式 */
.right-section {
  width: 550px;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%);
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content {
  width: 100%;
  max-width: 400px;
}

/* 标题样式 */
.title-section {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.title-section h1 {
  font-family: 'STXingkai', 'STZhongsong', serif;
  font-size: 48px;
  color: #FFD700;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  letter-spacing: 8px;
  padding-bottom: 15px;
  position: relative;
}

.title-section h1::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 180px;
  height: 2px;
  background: linear-gradient(90deg,
      transparent,
      rgba(255, 215, 0, 0.3),
      #FFD700,
      rgba(255, 215, 0, 0.3),
      transparent);
}

.title-section p {
  font-size: 18px;
  color: #FFD700;
  margin-top: 15px;
  font-family: 'STZhongsong', sans-serif;
  letter-spacing: 4px;
}

/* 表单主标题 */
.form-title {
  text-align: center;
  color: #FFD700;
  font-size: 24px;
  margin: 0 0 20px;
  font-family: 'STZhongsong', sans-serif;
  letter-spacing: 2px;
}

/* 注册框样式 */
.register-box {
  background: rgba(0, 0, 0, 0.2);
  padding: 30px;
  border-radius: 10px;
  border: 1px solid rgba(255, 215, 0, 0.3);
}

/* 输入框样式 */
.el-input>>>.el-input__inner {
  height: 45px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 215, 0, 0.3);
  color: #fff;
  border-radius: 6px;
  padding-left: 45px;
  font-size: 15px;
}

.el-input>>>.el-input__inner:focus {
  border-color: #FFD700;
}

.el-input>>>.el-input__prefix {
  color: #FFD700;
  font-size: 18px;
  left: 15px;
}

/* 验证码按钮样式 */
.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group .el-input {
  flex: 1;
}

.code-btn {
  width: 100px !important;
  height: 45px !important;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%) !important;
  border: 1px solid #FFD700 !important;
  color: #FFD700 !important;
  font-size: 14px !important;
  padding: 0 15px !important;
  border-radius: 6px !important;
  transition: all 0.3s !important;
}

.code-btn:hover:not([disabled]) {
  opacity: 0.9;
  border-color: #fff !important;
  color: #fff !important;
}

.code-btn[disabled] {
  background: rgba(139, 0, 0, 0.5) !important;
  border-color: rgba(255, 215, 0, 0.3) !important;
  color: rgba(255, 215, 0, 0.5) !important;
  cursor: not-allowed;
}

/* 注册按钮 */
.el-button--primary {
  width: 100%;
  height: 45px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid #FFD700;
  font-size: 16px;
  letter-spacing: 4px;
  border-radius: 6px;
  margin-top: 15px;
  color: #FFD700;
}

.el-button--primary:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-top: 20px;
  color: rgba(255, 215, 0, 0.8);
  font-size: 14px;
}

.login-link a {
  color: #FFD700;
  text-decoration: none;
  margin-left: 5px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .right-section {
    width: 500px;
  }

  .title-section h1 {
    font-size: 42px;
  }
}

@media (max-width: 992px) {
  .left-section {
    display: none;
  }

  .right-section {
    width: 100%;
  }
}

@media (max-width: 576px) {
  .right-section {
    padding: 20px;
  }

  .register-box {
    padding: 20px;
  }

  .title-section h1 {
    font-size: 36px;
  }
}
</style>